package org.phalanx.client.net;

import org.phalanx.messenging.AuthenticationMessage;
import org.phalanx.messenging.management.MessageListener;
import org.phalanx.messenging.management.PhalanxMetaMessage;

public class AuthenticationManager implements MessageListener{
	private PhalanxConnectionManager phalanxCm;
	public static final int NOT_CONNECTED = 0;
	public static final int CONNECTED = 1;
	private int state;
	String serverNode;
	
	public AuthenticationManager(PhalanxConnectionManager pM) {
		this.phalanxCm = pM;
		state = NOT_CONNECTED;
	}
	
	public void logIn(String serverNode) {
		AuthenticationMessage requestMsg = new AuthenticationMessage();
		requestMsg.setAction(AuthenticationMessage.LOGIN_REQUEST);
		
		//phalanxCm.getMessageManager().sendMessage(requestMsg, phalanxCm.createChatObject(serverNode));
	}
	
	
	public void processMessage(AuthenticationMessage msg, PhalanxMetaMessage pMsg) {
		if (msg.getRequest() != null) {
			if (msg.getRequest().equals(AuthenticationMessage.NOT_AUTH)) {
				// Auth to the server
				auth(pMsg.getUserName());
			}
			else if (msg.getRequest().equals(AuthenticationMessage.AUTH_OK)) {
				logIn(pMsg.getUserName());
			}
			else if (msg.getRequest().equals(AuthenticationMessage.LOGIN_OK)) {
				// Login Ok
				state = CONNECTED;
			}
			else if (msg.getRequest().equals(AuthenticationMessage.ALREADY_LOGIN)) {
				state = CONNECTED;
			}
		}
	}
	
	public int getState() {
		return state;
	}
	
	private void auth(String serverNode) {
		AuthenticationMessage requestMsg = new AuthenticationMessage();
		requestMsg.setAction(AuthenticationMessage.AUTH_REQUEST);
		
		//phalanxCm.getMessageManager().sendMessage(requestMsg, phalanxCm.createChatObject(serverNode));
	}
	
/*	public void logOut(String serverNode) {
		AuthenticationMessage requestMsg = new AuthenticationMessage();
		requestMsg.setAction(AuthenticationMessage.);
		
		phalanxCm.getMessageManager().sendMessage(requestMsg, phalanxCm.createChatObject(serverNode));
	}*/
}
